package com.cb.web.wasf.tag;

import com.cb.web.wasf.DefaultSession;
import com.cb.web.wasf.Request;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.tagext.TryCatchFinally;

/**
 * @author CBO
 */
public class FormTag extends TagSupport implements TryCatchFinally {

    @Override
    public int doStartTag() throws JspException {
        StringBuilder sb = new StringBuilder();
        // @TODO : Handle special characters
        sb.append("<form method=\"post\" id=\"").append(getId()).append("\">");
        sb.append("<input type=\"hidden\" id=\"").append(getId()).append("-" + Request.EVENT_RPN).append("\" name=\"").append(Request.EVENT_RPN).append("\" value=\"\">");
        sb.append("<input type=\"hidden\" id=\"").append(getId()).append("-" + Request.EVENT_SOURCE_RPN).append("\" name=\"").append(Request.EVENT_SOURCE_RPN).append("\" value=\"\">");
        sb.append("<input type=\"hidden\" id=\"").append(getId()).append("-" + DefaultSession.SESSION_ID_RPN).append("\" name=\"").append(DefaultSession.SESSION_ID_RPN).append("\" value=\"").append(DefaultSession.getFromPageContext(pageContext).getId()).append("\">");
        sb.append("<input type=\"hidden\" id=\"").append(getId()).append("-" + DefaultSession.SESSION_REQUEST_ID_RPN).append("\" name=\"").append(DefaultSession.SESSION_REQUEST_ID_RPN).append("\" value=\"").append(DefaultSession.getFromPageContext(pageContext).getRequestId()).append("\">");
        try {
            pageContext.getOut().print(sb.toString());
        } catch (IOException ioe) {
            throw new JspException(ioe);
        }
        return EVAL_BODY_INCLUDE;
    }

    @Override
    public int doEndTag() throws JspException {
        StringBuilder sb = new StringBuilder();
        sb.append("</form>");
        try {
            pageContext.getOut().print(sb.toString());
        } catch (IOException ioe) {
            throw new JspException(ioe);
        }
        return EVAL_PAGE;
    }

    @Override
    public void doCatch(Throwable throwable) throws Throwable {
        throw throwable;
    }

    @Override
    public void doFinally() {
        setId(null);
    }

}
